<template>
  <div class="image-compression-test">
    <n-card title="图片压缩测试" class="test-card">
      <n-space vertical>
        <n-upload
          ref="uploadRef"
          :file-list="fileList"
          @update:file-list="handleFileListChange"
          list-type="image-card"
          :max="5"
          :custom-request="customUpload"
          accept="image/*"
          @change="handleChange"
        >
          <div class="upload-trigger">
            <n-icon size="48" :depth="3">
              <AddIcon />
            </n-icon>
            <n-text style="font-size: 12px; margin-top: 8px">
              选择图片进行压缩测试
            </n-text>
          </div>
        </n-upload>

        <n-divider />

        <n-space vertical>
          <n-text strong>压缩统计</n-text>
          <n-space>
            <n-tag type="info">总文件数: {{ fileList.length }}</n-tag>
            <n-tag type="success">压缩成功: {{ compressionStats.success }}</n-tag>
            <n-tag type="warning">压缩失败: {{ compressionStats.failed }}</n-tag>
            <n-tag type="error">上传失败: {{ compressionStats.uploadFailed }}</n-tag>
          </n-space>

          <n-text strong>大小统计</n-text>
          <n-space>
            <n-tag type="info">原始总大小: {{ formatFileSize(compressionStats.totalOriginalSize) }}</n-tag>
            <n-tag type="success">压缩后总大小: {{ formatFileSize(compressionStats.totalCompressedSize) }}</n-tag>
            <n-tag type="warning">总节省: {{ formatFileSize(compressionStats.totalSaved) }}</n-tag>
            <n-tag type="error">平均压缩率: {{ compressionStats.averageRatio.toFixed(1) }}%</n-tag>
          </n-space>
        </n-space>

        <n-divider />

        <n-space vertical>
          <n-text strong>详细结果</n-text>
          <n-table :bordered="false" :single-line="false">
            <thead>
              <tr>
                <th>文件名</th>
                <th>原始大小</th>
                <th>压缩后大小</th>
                <th>压缩率</th>
                <th>状态</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in compressionResults" :key="item.id">
                <td>{{ item.fileName }}</td>
                <td>{{ formatFileSize(item.originalSize) }}</td>
                <td>{{ formatFileSize(item.compressedSize) }}</td>
                <td>
                  <n-tag :type="item.compressionRatio > 50 ? 'success' : item.compressionRatio > 20 ? 'warning' : 'info'">
                    {{ item.compressionRatio.toFixed(1) }}%
                  </n-tag>
                </td>
                <td>
                  <n-tag :type="item.status === 'success' ? 'success' : item.status === 'failed' ? 'error' : 'warning'">
                    {{ item.status === 'success' ? '成功' : item.status === 'failed' ? '失败' : '压缩失败' }}
                  </n-tag>
                </td>
              </tr>
            </tbody>
          </n-table>
        </n-space>
      </n-space>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useMessage } from 'naive-ui'
import type { UploadFileInfo } from 'naive-ui'
import { Add as AddIcon } from '@vicons/ionicons5'
import { smartCompress, formatFileSize } from '../../utils/imageCompression'

const message = useMessage()
const uploadRef = ref()
const fileList = ref<UploadFileInfo[]>([])
const compressionResults = ref<Array<{
  id: string
  fileName: string
  originalSize: number
  compressedSize: number
  compressionRatio: number
  status: 'success' | 'failed' | 'compression_failed'
}>>([])

// 压缩统计
const compressionStats = computed(() => {
  const results = compressionResults.value
  const success = results.filter(r => r.status === 'success').length
  const failed = results.filter(r => r.status === 'failed').length
  const compressionFailed = results.filter(r => r.status === 'compression_failed').length

  const totalOriginalSize = results.reduce((sum, r) => sum + r.originalSize, 0)
  const totalCompressedSize = results.reduce((sum, r) => sum + r.compressedSize, 0)
  const totalSaved = totalOriginalSize - totalCompressedSize
  const averageRatio = results.length > 0
    ? results.reduce((sum, r) => sum + r.compressionRatio, 0) / results.length
    : 0

  return {
    success,
    failed,
    uploadFailed: failed,
    totalOriginalSize,
    totalCompressedSize,
    totalSaved,
    averageRatio
  }
})

// 处理文件列表变化
const handleFileListChange = (files: UploadFileInfo[]) => {
  fileList.value = files
}

// 处理文件变化
const handleChange = (options: { fileList: UploadFileInfo[] }) => {
  console.log('文件变化:', options.fileList)
}

// 自定义上传处理
const customUpload = async ({ file }: { file: UploadFileInfo }) => {
  console.log('开始处理文件:', file)

  try {
    const fileObj = file.file as File
    const resultId = Math.random().toString(36).substr(2, 9)

    // 记录原始信息
    const originalSize = fileObj.size
    let compressedSize = originalSize
    let compressionRatio = 0
    let status: 'success' | 'failed' | 'compression_failed' = 'success'

    // 如果是图片，进行压缩
    if (fileObj.type.startsWith('image/')) {
      try {
        console.log('压缩图片:', fileObj.name, '原始大小:', formatFileSize(originalSize))

        const compressionResult = await smartCompress(fileObj)
        compressedSize = compressionResult.compressedSize
        compressionRatio = compressionResult.compressionRatio

        console.log('压缩完成:', {
          原始大小: formatFileSize(compressionResult.originalSize),
          压缩后大小: formatFileSize(compressionResult.compressedSize),
          压缩比例: compressionResult.compressionRatio.toFixed(1) + '%'
        })

        // 更新文件对象
        file.file = compressionResult.file

        if (compressionRatio > 30) {
          message.info(`图片已压缩 ${compressionRatio.toFixed(1)}%，从 ${formatFileSize(originalSize)} 压缩到 ${formatFileSize(compressedSize)}`)
        }

      } catch (compressionError) {
        console.warn('压缩失败:', compressionError)
        message.warning('图片压缩失败，将使用原文件')
        status = 'compression_failed'
        compressedSize = originalSize
        compressionRatio = 0
      }
    }

    // 模拟上传成功
    file.url = URL.createObjectURL(file.file as File)
    file.status = 'finished'

    // 记录结果
    compressionResults.value.push({
      id: resultId,
      fileName: fileObj.name,
      originalSize,
      compressedSize,
      compressionRatio,
      status
    })

    message.success('处理完成')

  } catch (error) {
    console.error('处理失败:', error)
    file.status = 'error'
    message.error('处理失败')

    // 记录失败结果
    const fileObj = file.file as File
    compressionResults.value.push({
      id: Math.random().toString(36).substr(2, 9),
      fileName: fileObj.name,
      originalSize: fileObj.size,
      compressedSize: fileObj.size,
      compressionRatio: 0,
      status: 'failed'
    })
  }
}
</script>

<style scoped>
.image-compression-test {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.test-card {
  margin-bottom: 20px;
}

.upload-trigger {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 20px;
}
</style>
